package com.example.houtai.service.impl;

import com.example.houtai.entity.SysUser;
import com.example.houtai.entity.TbToken;
import com.example.houtai.mapper.SysUserMapper;
import com.example.houtai.mapper.TbTokenMapper;
import com.example.houtai.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.org.dto.UserDto;
import com.org.util.MD5Utils;
import com.org.vo.ResultEntity;
import com.org.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author 龚梦
 * @since 2021-03-22
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private TbTokenMapper tbTokenMapper;


    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static Date now = new Date();


    @Override
    public PageInfo<UserDto> lists(UserDto userDto) {
        PageHelper.startPage(userDto.getPageNum(),userDto.getPageSize());
        List<UserDto> list=userMapper.lists(userDto);
        PageInfo<UserDto> info=new PageInfo<>(list);
        return info;
    }

    @Override
    public SysUser seluserbymobile(String mobile) {
        return userMapper.seluserbymobile(mobile);
    }

    @Override
    public SysUser seluserbyusername(String username, String password) {
        return userMapper.seluserbyusername(username,password);
    }


    @Override
    public ResultEntity login(UserDto userDto, HttpServletResponse response) {
       /* Cookie cookie=new Cookie("auth", RandomUtil.uuid());
        if (userDto.getMobile().equals("admin") || userDto.getMobile().equals("test")){
            SysUser sysUser=userMapper.seluserbyusername(userDto.getMobile(), MD5Utils.md5(userDto.getPassword()));
            log.info("===管理员用户名密码登录=="+sysUser);
            if (sysUser!=null){
                // redisTemplate.opsForValue().set("token",sysUser);
                TbToken tbToken =tbTokenMapper.SelectTokenByUid(sysUser.getUserId());
                if (tbToken!=null){
                    if (now.getTime()>=tbToken.getExpireTime().getTime()){
                        boolean b = this.updateToken(sysUser);
                        if (b){
                            log.info("保存token成功");
                        }
                    }
                    cookie.setPath("/");
                    cookie.setDomain("localhost");
                    cookie.setMaxAge(-1);
                    response.addCookie(cookie);
                }else{
                    boolean b = this.insertToken(sysUser);
                    if (b){
                        log.info("保存token成功");
                    }
                }
                log.info("查询token中userId为登录id的信息"+tbToken);
                return ResultEntity.ok("以管理者身份登录成功");
            }
        }else{
            SysUser sysUser=userMapper.seluserbymobile(userDto.getMobile());
            log.info("====登录后根据手机号查询=="+sysUser);
            if (sysUser==null){
                return ResultEntity.error("登录失败无用户");
            }
            //String password = userDto.getPassword();
            if (!sysUser.getPassword().equals(MD5Utils.md5(userDto.getPassword()))) {
                return ResultEntity.error("失败密码错误");
            }else{
                TbToken tbToken =tbTokenMapper.SelectTokenByUid(sysUser.getUserId());
                log.info("查询token中userId为登录id的信息"+tbToken);
                cookie.setPath("/");
                cookie.setDomain("localhost");
                cookie.setMaxAge(-1);
                response.addCookie(cookie);
                //  redisTemplate.opsForValue().set("token",sysUser);
                return ResultEntity.ok("登录成功密码正确");
            }
        }*/
        return ResultEntity.ok("登录成功");
    }

    @Override
    public SysUserVo findByUserName(String username) {
        return userMapper.findByUserName(username);
    }


    public boolean insertToken(SysUser sysUser){
        TbToken tbToken1=new TbToken();
        tbToken1.setUserId(sysUser.getUserId().toString());
        //tbToken1.setToken(RandomUtil.uuid());
        Date afterDate = new Date(now .getTime() + 300000);
        tbToken1.setExpireTime(afterDate);
        tbToken1.setUpdateTime(now);
         int insert = tbTokenMapper.insert(tbToken1);
         if (insert>0){
             return true;
         }else{
             return false;
         }
    }


    public boolean updateToken(SysUser sysUser){
        TbToken tbToken1=new TbToken();
        tbToken1.setUserId(sysUser.getUserId().toString());
       // tbToken1.setToken(RandomUtil.uuid());
        Date afterDate = new Date(now .getTime() + 300000);
        tbToken1.setExpireTime(afterDate);
        tbToken1.setUpdateTime(now);
        int insert = tbTokenMapper.updateById(tbToken1);
        if (insert>0){
            return true;
        }else{
            return false;
        }
    }


}
